package client;

import cn.hutool.json.JSONUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author Lyoto
 * @Description
 * @Date 2022-10-24 23:01
 * @Version
 **/
public class Connector {
    public boolean connect(String url) {
        String host = "localhost";
        int port = 80;
        if (url.contains(":")) {
            String[] split = url.split("\\:");
            host = split[0];
            port = Integer.parseInt(split[1].substring(0, split[1].indexOf("//")));
        }
        try (Socket socket = new Socket(host, port)) {
            socket.setKeepAlive(true);
            socket.connect(new InetSocketAddress(host, port), 500);
            System.out.println("已连接");
            Scanner scanner = new Scanner(socket.getInputStream());
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
            Scanner console = new Scanner(System.in);
            while (true) {
                String msg4Server = JSONUtil.formatJsonStr(scanner.next());
                System.out.println("响应：\n"+msg4Server);
                System.out.println("输入json串");
                String msg4Console = console.nextLine();
                printWriter.write(msg4Console + "\r\n");
                printWriter.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    
}
